package com.zhenyi.core.sms;

import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

import cn.hutool.core.util.RandomUtil;

public abstract class SMSHandler {

	private static final String INTERVAL_KEY = "-zhenyi-interval";
	private static final String VERIFY_KEY = "-zhenyi";

	protected Cache cache = Redis.use();

	private static String genCode() {
		String code = RandomUtil.randomInt(1000000, 9999999) + "";
		// code = code.substring(3, code.length());
		// 6位验证码
		// System.out.println(code.substring(1, code.length()));
		// 4位验证码
		// System.out.println(code.substring(3, code.length()));
		return code.substring(3, code.length());
	}

	/**
	 * 短信项目,缓存存放标志
	 * 
	 * @return
	 */
	protected String projectKey() {
		String key = getProjectKey();
		if (StrKit.isBlank(key)) {
			return "ZhenyiProject";
		}
		return key;
	}

	public final Ret sendSMS(String mobile) {
		return sendSMS(mobile, false);
	}

	/**
	 * 发送短信
	 * 
	 * @param mobile
	 *            电话号码
	 * @param isForce
	 *            是否强制发送
	 * @return
	 */
	public final Ret sendSMS(String mobile, boolean isForce) {
		if (!isForce) {
			if (checkInterval(mobile)) {
				return Ret.fail();
			}
		}
		String code = genCode();
		Ret ret = onSend(mobile, code);
		if (ret == null) {
			return Ret.fail();
		}
		if (ret.isOk()) {
			try {
				String key = mobile + VERIFY_KEY + projectKey();
				String intervalKey = mobile + INTERVAL_KEY + projectKey();
				cache.setex(key, 300, code);
				cache.setex(intervalKey, 60, 1);
			} catch (Exception e) {
				LogKit.warn("redis error");
			}
			return ret;
		}
		return ret;
	}

	/**
	 * 处理发送过程(验证码5分钟有效)
	 * 
	 * @param mobile
	 * @param code
	 * @return
	 */
	protected abstract Ret onSend(String mobile, String code);

	protected abstract String getProjectKey();

	/**
	 * 校验验证码
	 * 
	 * @param mobile
	 * @param code
	 * @return
	 * @Time 2018年12月11日 下午4:07:38
	 */
	public boolean verify(String mobile, String code) {
		String key = mobile + VERIFY_KEY + projectKey();
		Cache cache = Redis.use();
		if (cache.exists(key) && cache.get(key).equals(code)) {
			return true;
		}
		return false;
	}

	/**
	 * 检查是否在 60s 内
	 * 
	 * @param mobile
	 * @return true 60s之内; false 60s之后
	 */
	protected boolean checkInterval(String mobile) {
		String key = mobile + INTERVAL_KEY + projectKey();
		Cache cache = Redis.use();
		if (cache.exists(key)) {
			return true;
		}
		return false;
	}

}
